<?php


namespace app\agent\controller\agent;

use app\agent\controller\Controller;
use app\agent\model\agent\Agent as AgentModel;
use app\agent\model\agent\User as AgentUserModel;
use think\Session;
use think\Db;
use utils\Random;
use think\Config;


class User extends Controller{
    /**
     * 代言人首页
     */
    public function index(){
        $session = Session::get('yoshop_agent');
        $agent_id = $session['agent']['agent_id'];
        //获取当前登录人可添加的免费代言人数量
        //授权数量
        $shouquanCout=$session['agent']['employees_num'];
        //剩余数量
        $may=Db::name('agent')->where(['recommend_id'=>$agent_id,'type'=>3])->count();
        $can=$shouquanCout-$may;
        if($can==0||$can<0){
            $can=0;
        }
        $ss['shouquan']=$shouquanCout;
        $ss['can']=$can;
        $model = new AgentModel;
        var_dump($agent_id);
        return $this->fetch('index', [
            'list' => $list = $model->getperList($agent_id,3),
            'amount'=>$ss
        ]);
    }
    
    /*
     * 冻结开启代言人权限
     */
    public function editUser(){
        $name=input('claickclass');
        $data['agent_id']=input('agent_id');
        if($name=='am-icon-trashqy'){
            $is_delete=0;
            $active=1;
            $status=1;
        }else{
            $is_delete=1;
            $active=0;
            $status=0;
        }
        Db::name('agent')->where(['agent_id' => $data['agent_id']])->update(['is_delete'=>(int)$is_delete,'active'=>(int)$active,'status'=>(int)$status]);
        Db::name('agent_user')->where(['agent_user_id' => $data['agent_id']])->update(['is_delete'=>(int)$is_delete,'active'=>(int)$active,'status'=>(int)$status]);
        return json(['code'=>1]);
    }
    /*
     * 审核代言人
     */
    public function checkout(){
        $agentId=input('agent_id');
        Db::name('agent')->where(['agent_id'=>$agentId])->update(['agent_check_status'=>1]);
        Db::name('agent_user')->where(['agent_user_id'=>$agentId])->update(['agent_check_status'=>1]);
        return json(['msg'=>'操作成功','code'=>'1','data'=>[]]);
    }
    /**
     * 添加代言人
     */
    public function add(){
        if (!$this->request->isAjax()) {

            return $this->fetch('add');
        }
        $model = new AgentModel;
        $session = Session::get('yoshop_agent');
        $data = $this->postData('agent');
        //判断当前用户添加的代言人是否需要激活
        //授权数量
        $shouquanCout=$session['agent']['employees_num'];
        //已添加的代言人数量
        $may=Db::name('agent')->where(['recommend_id'=>$session['agent']['agent_id'],'type'=>3])->count();
        if($may>=$shouquanCout){
            //需要品牌商通过  总后台激活
            $active=0;//需要总后台审核更新
            $agent_check_status=0;
            $admin_check_status=0;
        }else{
            $active=1;
            $agent_check_status=1;
            $admin_check_status=1;
        }

        $infos1=Db::name('agent')->where(['user_name'=>$data['user_name']])->find();
        if(!empty($infos1)){
            return $this->renderError('代言人登录名不能重复');
        }
        Db::startTrans();
        try{
            $data['recommend_id'] = $session['agent']['agent_id'];
            $agentOneInfo=Db::name('agent')->where(['pinpai_id'=>$session['agent']['pinpai_id'],'user_name'=>$data['user_name']])->find();
            if($agentOneInfo){
                return $this->renderError($model->getError() ?: '登录名已被占用，请重新输入');
            }

            if($data['password']!=$data['password_confirm']){
                return $this->renderError($model->getError() ?: '两次输入的密码不一致，添加失败');
            }
            //手机号码格式验证
            if(!preg_match("/^[1]([3-9])[0-9]{9}$/",$data['company_tel'])){
                return $this->renderError('联系电话格式有误请重新输入');
            }
            //获取上级所在公司名称
            $companyInfo=$model->getAgentInfo($data['recommend_id']);
            if(!empty($companyInfo)&&$companyInfo['company_name']!=''){
                $company=$companyInfo['company_name'];
            }else{
                $company='代言人';
            }
            $dataInfo['prefix']='';//所属品牌商登录名前缀
            $dataInfo['pinpai_id']=$session['agent']['pinpai_id'];//所属品牌商id
            $dataInfo['recommend_id']=$data['recommend_id'];//上级id（0，系统添加，没有上级推荐人）
            $dataInfo['company_name']=$company;//代言人所在公司名称
            $dataInfo['type']=$data['type'];//代理商身份（0，品牌商，1.城市运营商，2.城市合伙人，3.代言人）
            $dataInfo['real_name']=$data['real_name'];//代言人姓名
            $dataInfo['company_tel']=$data['company_tel'];//代言人联系电话
            //$dataInfo['service_charge']=$data['service_charge'];//代言人参与的分红百分比
            $dataInfo['user_name']=$data['user_name'];//登录账户名称
            $salt=Random::alnum();

            $dataInfo['salt']=$salt;//密码盐
            $dataInfo['password']= md5(md5($data['password'].$salt.config('salt')));

            //$dataInfo['reward']=$data['reward'];;//代言人推荐获得的奖金
            $dataInfo['is_recycle']=0;//是否回收
            $dataInfo['is_delete']=0;//是否删除
            $dataInfo['status']=1;//是否启用
            $dataInfo['is_super']=1;//是否超级管理员
            $dataInfo['create_time']=time();//创建时间
            $dataInfo['update_time']=0;//更新时间
            $dataInfo['finish_time']=time()+864000;//过期时间
            $dataInfo['active']=$active;//账户激活（0，未激活，1.已激活）代言人默认激活
            $dataInfo['agent_check_status']=$agent_check_status;
            $dataInfo['admin_check_status']=$admin_check_status;
            //新增记录
            $agentId=$model->add($dataInfo);
            //新增agent_user数据
            $agentUserModel=new AgentUserModel();
            $dataInfo['agent_id']=$agentId;
            $agentUserModel->add($dataInfo);
            Db::commit();
            return $this->renderSuccess('添加成功',url('agent.user/index'));
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError('添加失败');
        }
    }
}